﻿using Microsoft.Extensions.Options;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RedisNet
{
    public class RedisClient
    {
        private readonly Lazy<ConnectionMultiplexer> _lazyConnection;
        private readonly RedisConfigOptions _config;

        public RedisClient(IOptions<RedisConfigOptions> configOptions)
        {
            _config = configOptions.Value;

            _lazyConnection = new Lazy<ConnectionMultiplexer>(() =>
            {
                var configurationOptions = new ConfigurationOptions
                {
                    EndPoints = { $"{_config.Host}:{_config.Port}" },
                    Password = _config.Password,
                    Ssl = _config.Ssl,
                    AbortOnConnectFail = _config.AbortOnConnectFail,
                    ConnectTimeout = _config.ConnectTimeout,
                    ConnectRetry = _config.ConnectRetry
                };

                return ConnectionMultiplexer.Connect(configurationOptions.ToString());
            });
        }

        public IDatabase GetDatabase() => _lazyConnection.Value.GetDatabase(_config.Database);

        public ConnectionMultiplexer GetConnection() => _lazyConnection.Value;
    }
}
